package slhs.tempo.scriptGenerator;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;

import slhs.tempo.dataImporterUtilities.OutFileFields;

/**
 * 
 */

/**
 * @author Administrator
 * 
 */
public class CsvImporter {

    private int numberOfLines = 0;
    private static final String SUBJECT_NAME_PATTERN = "Subject =";
    private static final String SUBJECT_STATUS_PATTERN = "Subject Status =";
    private static final String NOTES_PATTERN = "Notes:";
    private static final String TEMPLATE_FILE_PATH_PATTERN = "Template File =";

    private OutFileFields outFileFields;

    public CsvImporter(Object[] tableColoumns) {

    }

    public OutFileFields populateOutFileFields(String outFilePath) {
	String fileLine;
	outFileFields = new OutFileFields();
	numberOfLines = 0;

	try {
	    FileInputStream fileInputStream = new FileInputStream(outFilePath);
	    DataInputStream dataInputStream = new DataInputStream(fileInputStream);
	    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));
	    try {
		while ((fileLine = bufferedReader.readLine()) != null) {
		    if (fileLine.contains(SUBJECT_NAME_PATTERN)) {
			outFileFields.setSubjectName(fileLine.substring(SUBJECT_NAME_PATTERN.length()).trim());
		    }
		    if (fileLine.contains(SUBJECT_STATUS_PATTERN)) {
			outFileFields.setSubjectStatus(fileLine.substring(SUBJECT_STATUS_PATTERN.length()).trim());
		    }
		    if (fileLine.contains(NOTES_PATTERN)) {
			outFileFields.setNotes(fileLine.substring(NOTES_PATTERN.length()).trim());
		    }
		    if (fileLine.contains(TEMPLATE_FILE_PATH_PATTERN)) {
			outFileFields.setNotes(fileLine.substring(TEMPLATE_FILE_PATH_PATTERN.length()).trim());
		    }

		    if ((outFileFields.getSubjectName() != null)
			    && (fileLine.startsWith(outFileFields.getSubjectName()))) {
			// Ask user to identify columns
			String[] tableRow = fileLine.split(";");
			List<String> tableRowList = Arrays.asList(tableRow);
			outFileFields.addData(new Vector(tableRowList));
			// System.out.println(fileLine);
			numberOfLines++;
		    }

		}
	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }

	} catch (FileNotFoundException e) {
	    // TODO Auto-generated catch block
	    System.out.println("Could not open the file");
	    e.printStackTrace();
	}
	outFileFields.setNumberOfEntries(numberOfLines);
	return outFileFields;
    }

}
